/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "motor.h"
#include "oled.h"
#include "encoder.h"
#include "stdio.h"
#include "pid.h"
#include "cJSON.h"
#include "string.h"
#include "retarget.h"
#include "gw_grayscale_sensor.h"
#include "hw_pid.h"
#include "VL53L0x.h"
#include "mpu6050.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

#define GW_GRAY_ADDR GW_GRAY_ADDR_DEF
cJSON *cJsonData, *cJsonV1aue;
float p, i, d, a;
int tpid;
uint8_t ID;                                //定义用于存放ID号的变量
int16_t AX, AY, AZ, GX, GY, GZ;            //定义用于存放各个数据的变量

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define OLED 0
#define  VL53L0x 0
#define MPU60X0 1

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
void GET_CJSON_VAL(void);
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void) {

    /* USER CODE BEGIN 1 */
    volatile int ret_transmit;
    uint8_t i2c_cmd;

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_I2C1_Init();
    MX_I2C3_Init();
    MX_TIM2_Init();
    MX_TIM3_Init();
    MX_TIM4_Init();
    MX_TIM6_Init();
    MX_USART3_UART_Init();
    /* USER CODE BEGIN 2 */

#if OLED
    OLED_Init();
    OLED_Clear();
    OLED_SHOWSTRING(0, 0, "dsadas");
#endif

#if VL53L0x
    VL53L0x_init(&hi2c3);
#endif

    /**
     * 注册 USART1 用于重定�?????????????
    * 当然其他端口也行
    */
    RetargetInit(&huart3);    // 该句柄为全局定义，用于初始化你需要用的串�?????????????(笔�?�为USART1)
    // 串口中断初始�?????????????
    __HAL_UART_ENABLE_IT(&huart3, UART_IT_RXNE);
    // PWM初始�?????????????
    PWMA_START();
    PWMB_START();

    // 电机可以�?????????????�?????????????
    STBY_SET();

    // 编码器初始化
    ENCODERA_START();
    ENCODERB_START();
    ENCODERA_IRQ_START();
    ENCODERB_IRQ_START();
    ENCODER_READ_COUNTER_IRQ_START();

    // pid初始�?????????????
    PID_init();

    // 打开定时器中�?????
    HAL_TIM_Base_Start_IT(&htim2);
    HAL_TIM_Base_Start_IT(&htim6);
    // HAL_TIM_Base_Stop_IT(&htim2);

    i2c_cmd = GW_GRAY_DIGITAL_MODE;
    ret_transmit = HAL_I2C_Master_Transmit(&hi2c1, GW_GRAY_ADDR << 1, &i2c_cmd, 1, 100);

    if (ret_transmit != HAL_OK) {
        ret_transmit = HAL_I2C_Master_Transmit(&hi2c1, GW_GRAY_ADDR << 1, &i2c_cmd, 1, 100);
        // i2c 错误
        /* 处理错误 */
        printf("ret_transmit = %d \r\n", ret_transmit);
        HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_SET);
        Error_Handler();
    }
    HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_RESET);

#if MPU60X0
    MPU6050_Init();
#endif

/* USER CODE END 2 */

/* Infinite loop */
/* USER CODE BEGIN WHILE */
    while (1) {
/* USER CODE END WHILE */

/* USER CODE BEGIN 3 */
        HAL_GPIO_TogglePin(LED0_GPIO_Port, LED0_Pin);
        HAL_GPIO_TogglePin(LED1_GPIO_Port, LED1_Pin);
        HAL_Delay(500);
// GET_CJSON_VAL();
        MPU6050_GetData(&AX, &AY, &AZ, &GX, &GY, &GZ);        //获取MPU6050的数据
        //printf("| %d %d %d \r\n | --- ", AX, AY, AZ);
        printf("||%d %d %d \r\n ||", GX, GY, GZ);
    }
/* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void) {
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    /** Configure the main internal regulator output voltage
    */
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
    RCC_OscInitStruct.PLL.PLLM = 8;
    RCC_OscInitStruct.PLL.PLLN = 168;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = 4;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                  | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) {
        Error_Handler();
    }
}

/* USER CODE BEGIN 4 */
// {"tpid":1,"p":16,"i":5,"d":1,"a":2}
void GET_CJSON_VAL(void) {
    if (Uart_WaitReasFinish() == 0)//是否接收完毕
    {
        cJsonData = cJSON_Parse((const char *) Usart3_ReadBuf);

        if (cJSON_GetObjectItem(cJsonData, "tpid") != NULL) {
            cJsonV1aue = cJSON_GetObjectItem(cJsonData, "tpid");
            tpid = cJsonV1aue->valuedouble;
        }
        if (cJSON_GetObjectItem(cJsonData, "p") != NULL) {
            cJsonV1aue = cJSON_GetObjectItem(cJsonData, "p");
            p = cJsonV1aue->valuedouble;
        }
        if (cJSON_GetObjectItem(cJsonData, "i") != NULL) {
            cJsonV1aue = cJSON_GetObjectItem(cJsonData, "i");
            i = cJsonV1aue->valuedouble;
        }
        if (cJSON_GetObjectItem(cJsonData, "d") != NULL) {
            cJsonV1aue = cJSON_GetObjectItem(cJsonData, "d");
            d = cJsonV1aue->valuedouble;
        }
        if (cJSON_GetObjectItem(cJsonData, "a") != NULL) {
            cJsonV1aue = cJSON_GetObjectItem(cJsonData, "a");
            a = cJsonV1aue->valuedouble;
        }
        if (cJsonData != NULL) {
            cJSON_Delete(cJsonData);//释放空间、但是不能删除cJsonV1aue不然会出现异常错�?????????????
        }
        if (tpid == 1) {
            pidA.Kp = p;
            pidA.Ki = i;
            pidA.Kd = d;
            pidA.target_val = -a;
        } else if (tpid == 2) {
            pidB.Kp = p;
            pidB.Ki = i;
            pidB.Kd = d;
            pidB.target_val = -a;
        }
        memset(Usart3_ReadBuf, 0, 256);//清空接收buf,注意这里不能使用strlen
        printf("TPID :%d P:%.3f I:%.3f D:%.3f A:%.3f \r\n", tpid, p, i, d, a);
    }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void) {
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();

    while (1) {
        printf("Error_Handler");
    }
    /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
